<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : App.php
 * Created on : 2021-2-4 15:58:47
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\wechat\controller;

use app\Request;
use app\wechat\model\WechatApp;
use app\wechat\model\WechatAppAddons;
use app\wechat\model\WechatAppAddonsConfig;
use app\wechat\validate\WechatAppValidate;
use app\wechat\validate\WechatAppAddonsValidate;
use haoteam\service\UtilService;
use haoteam\service\WechatAppService;
use app\admin\model\AdminConfig;
use think\facade\View;
use think\facade\Db;

/**
 * 小程序管理
 * Class App
 * Tiger <1192851302@qq.com> 2021-2-4 15:58:47
 */
class App {

    /**
     * 小程序管理
     * @auth true
     * @menu true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function index(Request $request) {
        $post = UtilService::postMore([
                    'name',
                    'username'
        ]);
        $post['uid'] = $request->adminId();
        return app('json')->successful(WechatApp::getList($post));
    }

    /**
     * 添加小程序
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function create(Request $request) {
        $post = UtilService::postMore([
                    'name',
                    'appid',
                    'appsecret',
                    'origin_id',
                    'token',
                    'encodingaeskey',
                    'mchid',
                    'paysignkey',
                    'cert_path',
                    'key_path',
                    'logo'
        ]);
        $post['uid'] = $request->adminId();
        $post['token'] = $post['token'] ?: create_salt(32);
        $post['encodingaeskey'] = $post['encodingaeskey'] ?: create_salt(43);
        $validate = new WechatAppValidate();
        if ($validate->scene('create')->check($post) == false) {
            return app('json')->fail($validate->getError());
        }
        try {
            WechatApp::create($post);
        } catch (\Exception $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('创建成功');
    }

    /**
     * 更新小程序
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function update(Request $request) {
        $post = UtilService::postMore([
                    'id',
                    'name',
                    'appid',
                    'appsecret',
                    'origin_id',
                    'token',
                    'encodingaeskey',
                    'mchid',
                    'paysignkey',
                    'cert_path',
                    'key_path',
                    'logo'
        ]);
        $validate = new WechatAppValidate();
        if ($validate->scene('update')->check($post) == false) {
            return app('json')->fail($validate->getError());
        }
        $where['id'] = $post['id'];
        if ($request->isSuper() === false) {
            $where['uid'] = $request->adminId();
        }
        try {
            WechatApp::update($post, $where);
        } catch (\Exception $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('更新成功');
    }

    /**
     * 删除小程序
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function delete(Request $request) {
        [$id] = UtilService::postMore(['id'], $request, true);
        $validate = new WechatAppValidate();
        if ($validate->scene('delete')->check(compact('id')) == false) {
            return app('json')->fail($validate->getError());
        }
        $where['id'] = $id;
        if ($request->isSuper() === false) {
            $where['uid'] = $request->adminId();
        }
        try {
            WechatApp::update(['is_del' => 1], $where);
        } catch (\Exception $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('删除成功');
    }

    /**
     * 审核小程序
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function status(Request $request) {
        [$id, $status] = UtilService::postMore(['id', 'status'], $request, true);
        $validate = new WechatAppValidate();
        if ($validate->scene('delete')->check(compact('id')) == false) {
            return app('json')->fail($validate->getError());
        }
        try {
            WechatApp::update(compact('status'), compact('id'));
        } catch (\Exception $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('操作成功');
    }

    /**
     * 应用+
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function addon(Request $request) {
        $post = UtilService::postMore(['id', 'action', 'addon']);
        switch ($post['action']) {
            case 'write':
                $validate = new WechatAppValidate();
                if ($validate->scene('delete')->check($post) == false) {
                    return app('json')->fail($validate->getError());
                }
                try {
                    WechatApp::update(['addon' => $post['addon']], ['id' => $post['id']]);
                } catch (\Exception $exc) {
                    return app('json')->fail($exc->getMessage());
                }
                $return = '操作成功';
                break;
            case 'list':
            default:
                $return = WechatAppAddons::getList(['status' => 1]);
                break;
        }
        return app('json')->successful($return);
    }

    /**
     * 小程序应用管理
     * @auth true
     * @menu true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function addons(Request $request) {
        [$install] = UtilService::postMore([['install', 1]], $request, true);
        if ($install) {
            return app('json')->successful(WechatAppAddons::getList());
        }
        $return = WechatAppService::instance()->getAppList();
        $appList = [];
        foreach ($return as $item) {
            if (WechatAppAddons::count(['addon' => $item['addon']])) {
                continue;
            }
            $item['status'] = 0;
            $appList[] = $item;
        }
        return app('json')->successful([
                    'code' => 0,
                    'items' => $appList,
                    'total' => count($appList)
        ]);
    }

    /**
     * 应用安装
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function addons_install(Request $request) {
        [$addon] = UtilService::postMore(['addon'], $request, true);
        if (empty($addon)) {
            return app('json')->fail('应用标识不能为空');
        }
        $appInfo = WechatAppService::instance()->addonInfo;
        if (empty($appInfo)) {
            return app('json')->fail('应用配置文件不存在');
        }
        $validate = new WechatAppAddonsValidate();
        if ($validate->scene('install')->check($appInfo) == false) {
            return app('json')->fail($validate->getError());
        }
        if (WechatAppAddons::count(['addon' => $addon])) {
            return app('json')->fail('应用已安装，请先卸载应用再重新安装');
        }
        // 启动事务
        Db::startTrans();
        try {
            WechatAppService::instance()->execute_sql($appInfo['install_sql'] ?? '');
            WechatAppAddons::create($appInfo);
            // 提交事务
            Db::commit();
        } catch (\Exception $exc) {
            // 回滚事务
            Db::rollback();
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('安装成功');
    }

    /**
     * 应用卸载
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function addons_uninstall(Request $request) {
        [$addon] = UtilService::postMore(['addon'], $request, true);
        if (empty($addon)) {
            return app('json')->fail('应用标识不能为空');
        }
        $appInfo = WechatAppService::instance()->addonInfo;
        if (empty($appInfo)) {
            return app('json')->fail('应用配置文件不存在');
        }
        // 启动事务
        Db::startTrans();
        try {
            WechatAppService::instance()->execute_uninstall_sql($appInfo['install_sql'] ?? '');
            WechatAppAddons::destroy(['addon' => $addon]);
            //暂时不支持删除源文件
            // 提交事务
            Db::commit();
        } catch (\Exception $exc) {
            // 回滚事务
            Db::rollback();
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('卸载成功');
    }

    /**
     * 应用状态管理
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function addons_status(Request $request) {
        [$id, $status] = UtilService::postMore(['id', ['status', 1]], $request, true);
        $validate = new WechatAppAddonsValidate();
        if ($validate->scene('status')->check(compact('id', 'status')) == false) {
            return app('json')->fail($validate->getError());
        }
        try {
            WechatAppAddons::update(compact('status'), compact('id'));
        } catch (\Exception $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('操作成功');
    }

    /**
     * 升级应用
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function addons_update(Request $request) {
        [$addon] = UtilService::postMore(['addon'], $request, true);
        if (empty($addon)) {
            return app('json')->fail('应用标识不能为空');
        }
        $appInfo = WechatAppService::instance()->addonInfo;
        if (empty($appInfo)) {
            return app('json')->fail('应用配置文件不存在');
        }
        $version = WechatAppAddons::where(compact('addon'))->value('version');
        if (empty($version)) {
            return app('json')->fail('应用未安装，请先安装');
        }
        if ($appInfo['version'] <= $version) {
            return app('json')->fail('目前版本为最新，无需更新');
        }
        // 启动事务
        Db::startTrans();
        try {
            WechatAppService::instance()->execute_sql($appInfo['upgrade_sql'] ?? '');
            WechatAppAddons::update($appInfo, compact('addon'));
            // 提交事务
            Db::commit();
        } catch (\Exception $exc) {
            // 回滚事务
            Db::rollback();
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('升级成功');
    }

    /**
     * 应用控制台
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @param string $addon   应用标识
     * @param string $mid   小程序ID
     * @return type
     */
    public function console(Request $request, $addon, $mid) {
        View::assign([
            'app_menu' => WechatAppService::instance()->bindMeun(),
            'admin_name' => AdminConfig::getOne('admin_name'),
            'admin_url' => AdminConfig::getOne('admin_url')
        ]);
        return View::fetch();
    }

    /**
     * 应用设置
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function config(Request $request) {
        View::assign([
            'config' => WechatAppAddonsConfig::getAll()
        ]);
        return View::fetch();
    }

    /**
     * 保存应用设置
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function config_write(Request $request) {
        [$config] = UtilService::postMore(['config'], $request, true);
        try {
            WechatAppAddonsConfig::preserve($config);
        } catch (\Exception $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful('保存成功');
    }

    /**
     * 应用控制台
     * @auth true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @param strimg $nodes Description
     * @return type
     */
    public function view(Request $request, $nodes) {
        $appInfo = WechatApp::getMore(WechatAppService::instance()->mid);
        $request->macro('miniappInfo', function() use(&$appInfo) {
            return $appInfo;
        });
        $request->macro('mid', function() use(&$appInfo) {
            return $appInfo['id'];
        });
        $request->macro('addon', function() use(&$appInfo) {
            return $appInfo['addon'];
        });
        return WechatAppService::instance()->run($nodes);
    }

}
